<template>
    <el-dialog v-model="addDialog" title="员工添加" width="800">
        <el-form :inline="true" class="demo-form-inline" ref="formRef" :rules="formRules" :model="formData">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="工号" label-width="80" :required="true">
                        <el-input autocomplete="off" v-model="staffNo" disabled/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="真实姓名" label-width="80" prop="realName">
                        <el-input autocomplete="off" v-model="formData.realName"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="密码" label-width="80" :required="true" >
                        <el-input autocomplete="off" v-model="formData.password" disabled/>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="avatar">
                    <el-form-item label="头像" prop="photoUrl">
                        <el-upload
                                style="border: 1px solid grey;width: 40px;height: 40px;"
                                class="avatar-uploader"
                                :action="axios.defaults.baseURL + '/file/upload'"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                        >
                            <img :src="formData.photoUrl" class="photo" v-if="formData.photoUrl" alt=""/>
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="身份证号" label-width="80" prop="idCard">
                        <el-input autocomplete="off" v-model="formData.idCard" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="性别" label-width="80" prop="gender">
                        <el-radio-group autocomplete="off" v-model="formData.gender" placeholder="请选择你的性别">
                            <el-radio :value="1">男</el-radio>
                            <el-radio :value="0">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="手机号码" label-width="80" prop="phone">
                        <el-input autocomplete="off" v-model="formData.phone" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="出生日期" label-width="80" prop="dateOfBirth">
                        <el-date-picker
                                autocomplete="off"
                                v-model="formData.dateOfBirth"
                                type="date" placeholder="选择日期"
                                size="default"
                                :editable="false"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                                style="width: 100%;"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="所属组织" label-width="80" style="width: 276px" :required="true">
                      <el-tree-select
                          autocomplete="off"
                          v-model="formData.organizationId"
                          placeholder="选择组织"
                          :data="organizationList"
                          node-key="id"
                          label-key="organizationName"
                          default-expand-all
                          check-strictly
                      />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="岗位名称" label-width="80" prop="jobName">
                        <el-input autocomplete="off" v-model="formData.jobName" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="入职日期" label-width="80" prop="joinDate">
                        <el-date-picker
                                autocomplete="off"
                                v-model="formData.joinDate"
                                type="date" placeholder="选择日期"
                                size="default"
                                :editable="false"
                                format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="薪资" label-width="80" prop="salary">
                        <el-input autocomplete="off" v-model="formData.salary" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="教育背景" style="width: 95%;" prop="educationBackground">
                        <el-input type="textarea" autocomplete="off" v-model="formData.educationBackground" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="addDialog = false">关闭</el-button>
                <el-button @click="resetForm(formRef)">重置</el-button>
                <el-button @click="save(formRef)" type="primary">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
    import {defineEmits, defineModel} from "@vue/runtime-core";
    import {onMounted, reactive, ref} from "vue";
    import axios from '@/axios/index.js'
    import {ElMessage} from "element-plus";
    import {Plus} from "@element-plus/icons-vue";

    let addDialog = defineModel('addDialog')
    const emit = defineEmits(['loadData'])
    const staffNo = ref()
    const formRef = ref()

    let formData = reactive({
        staffNo:null,
        password: '123456',
        gender: 1,
        realName:null,
        idCard:null,
        phone:null,
        dateOfBirth:null,
        organizationId:null,
        jobName:null,
        salary:null,
        createBy:'1',
        educationBackground:null,
        photoUrl:null,
        joinDate:null,
        createTime:null,
        status:'1',
        pid:'',
    })
      //学科集合
    let subjectNameList = ref([])

    //表单校验
    const formRules = reactive({
        /*staffNo: [
          {required:true,pattern: '^[a-zA-Z][a-zA-Z0-9]{5,9}$',message:'第一个字符为字母其余为数字',trigger: 'blur'},
          {max:10,message: '班级名不超过十位数'}
        ],*/
        realName: [
          {required: true,message: '输入真实姓名', trigger: 'blur'},
          {min:2,max:20,message: "真实姓名为2~20位非空字符"},
          {pattern:'^([\\u4e00-\\u9fa5]{2,20}|[a-zA-Z.\s]{2,20}|[a-zA-Z.\s\\u4e00-\\u9fff]{2,20})$',message:'请输入正确的真实姓名格式',trigger: 'blur'},
        ],
        idCard: [
          {required: true,message: '输入身份证号', trigger: 'blur'},
          {pattern:'^\\d{6}((1[0-9]|[2-9]\\d)\\d{2})(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\\d{3}[\\dXx]$', message: '请输入正确的身份证号格式',trigger: 'blur'},
        ],
        gender: [
          {required: true,message: '输入性别', trigger: 'blur'},
          {required:true, message: '性别不能为空',trigger: 'blur'}],
        /*phone: [{required:true,pattern:'^1\\d{10}$',message:'手机号码格式不正确',trigger: 'blur'}],*/
        phone: [
          {required: true,message: '输入手机号', trigger: 'blur'},
          {pattern:'^1[3-9]\\d{9}$',message:'请输入正确的手机号码格式',trigger: 'blur'}
        ],
        dateOfBirth: [{required:true, message: '出生日期不能为空',trigger: 'blur' }],
        organizationId: [{required:true, message: '组织不能为空',trigger: 'blur' }],
        jobName: [
          {required: true,message: '输入工作岗位', trigger: 'blur'},
          {min:2,max:15,message: "岗位名称为2~15位非空字符"},
          {pattern: '^[a-zA-Z.\s\\u4e00-\\u9fff\\-_]+$', message: '请输入正确的岗位名称格式',trigger: 'blur'},
          /*{
            validator:(rule, value, callback) => {
              // 去除前后空格
              const trimValue = value.trim()
              if (trimValue === '') {
                callback(new Error('岗位名称不能是空格'))
              }
            },
            trigger: 'blur'
          }*/
        ],
        salary: [
          {required: true,message: '输入薪资', trigger: 'blur'},
          {required:true,pattern:'^[0-9]{1,6}$',message:'请输入正确的薪资格式',trigger: 'blur'}
        ]
    })

    //保存用户
    const save = (formEl) => {
      if (!formRef) return
      formEl.validate((valid) => {
        if (valid) {
          formData.staffNo = staffNo.value
          axios.post('/staff/addStaff', formData).then(resp=>{
            ElMessage({
              message: resp.data.message,
              type: 'success',
              duration: 1500,
              onClose: function () {
                emit('loadData')
                addDialog.value = false
                //清除表单数据
                formData = {}
                // 刷新页面
                location.reload();
              }
            })
          })
        }
      })
    }

    //获取组织列表
    const getOrganizationList = async () => {
      try {
        const response = await axios.get('/organization/getList');
        return response.data.data.map(item => ({
          id: item.id,
          label: item.organizationName,
          children: item.children? item.children.map(child => ({
            id: child.id,
            label: child.organizationName
          })) : null
        }));
      } catch (error) {
        console.error('Error fetching organization list:', error);
        return [];
      }
    };
    let organizationList = [];
    (async () => {
      organizationList = await getOrganizationList();
    })();

    //上传头像
    function handleAvatarSuccess(response) {
        formData.photoUrl = response.data
        console.log(formData.photoUrl)
    }

    //重置表单校验
    const resetForm = (formEl) => {
        if (!formEl) return
        formEl.resetFields()
    }

    // 获取最后一条员工的编号
    onMounted(()=>{
      axios.get(`/staff/selectStaffNo`).then(resp=>{
        //console.log(resp.data.message)
        let temp = (resp.data.message).substring(2);
        staffNo.value = (+temp) + 1;
        while ((staffNo.value+"").length < 4) {//当字符串长度小于设定长度时，在前面加0
          staffNo.value = "0" + staffNo.value
        }
        staffNo.value = "HP"+staffNo.value
        //console.log(staffNo.value)
      })
    })

</script>

<style scoped>
    .demo-form-inline{
        margin-left: 40px;
    }
    .demo-form-inline .el-input{
        --el-input-width: 220px;
    }
    .demo-form-inline .el-radio-group{
        --el-input-width: 220px;
    }
    .demo-form-inline .el-date-picker{
        --el-input-width: 220px;
    }
    .demo-form-inline .el-col.el-col-12.avatar{
      padding: 0 40px;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 40px;
      height: 40px;
      text-align: center;
    }
    .avatar-uploader .photo {
        width: 40px;
        height: 40px;
        display: block;
    }
</style>
